import { ref, onMounted} from 'vue'

interface Cell {
  row: number
  col: number
  value: number | null
}

type ChessBoard = Cell[][]

export default function useGame() {
  
  // 棋盘
  const chessBoard = ref<ChessBoard>([])

  onMounted(() => {
    init()
  })

  /**
   * 游戏初始化
   */
  const init = () => {
    chessBoard.value.length = 0
    // 初始化 chessBoard 为一个 4x4 的二维数组，每个元素都是一个新的 Cell 实例
    for (let i = 0; i < 4; i++) {
      const row: Cell[] = []
      for (let j = 0; j < 4; j++) {
        row.push({ row: i, col: j, value: null })
      }
      chessBoard.value.push(row)
    }
    addNewNumber(chessBoard.value)
    addNewNumber(chessBoard.value)
  }

  /**
   * 在 chessBoard 中的随机空余位置上生成新的数字，其中：
   *    数字2 的几率为 90%
   *    数字4 的几率为 10%
   */
  const addNewNumber = (chessBoard: ChessBoard) => {
    const emptyCell = findEmptyCell(chessBoard)
    if (emptyCell) {
      chessBoard[emptyCell.row][emptyCell.col].value = Math.random() < 0.9 ? 2 : 4
    }
    chessBoard.forEach(row => console.log(row[0].value, row[1].value, row[2].value, row[3].value))
  }

  /**
   * 寻找 chessBoard 中空的位置，返回这些空位中的随机一个。
   */
  const findEmptyCell = (chessBoard: ChessBoard) => {
    const emptyCells: Cell[] = []
    for (let row = 0; row < chessBoard.length; row++) {
      for (let col = 0; col < chessBoard[row].length; col++) {
        if (chessBoard[row][col]?.value === null) {
          emptyCells.push({row, col, value: null})
        }
      }
    }
    return emptyCells.length > 0
      ? emptyCells[Math.floor(Math.random() * emptyCells.length)]
      : null
  }

  /**
   * 处理键盘事件的方法：↑ ↓ ← →
   * @param event 键盘事件
   */
  const handleKeyUp = (event: KeyboardEvent) => {
    switch(event.key) {
      case 'ArrowUp':
        move('up')
        break
      case 'ArrowDown':
        move('down')
        break
      case 'ArrowLeft':
        move('left')
        break
      case 'ArrowRight':
        move('right')
        break
    }
  }

  /**
   * 移动数组内的元素
   * @param direction 方向
   */
  const move = (direction: 'up' | 'down' | 'left' | 'right') => {
    console.log(direction)
    if (direction === 'up' || direction === 'down') {
      for (let col = 0; col < 4; col ++) {
        // 将棋盘中的每一列封装成新的数组之后对其进行移动操作
        const column = chessBoard.value.map(row => row[col])
        const newColumn = direction === 'up' ? slide(column) : slide(column.reverse()).reverse()
        newColumn.forEach((cell, row) => {
          cell.row = row
          cell.col = col
          chessBoard.value[row][col] = cell
        })
      }
    } else {
      for (let row = 0; row < 4; row ++) {
        // 将棋盘中的每一行封装成新的数组之后对其进行移动操作
        const newRow = direction == 'left' ? slide(chessBoard.value[row]) : slide(chessBoard.value[row].reverse()).reverse()
        newRow.forEach((cell, col) => {
          cell.row = row
          cell.col = col
          chessBoard.value[row][col] = cell
        })
      }
    }
    addNewNumber(chessBoard.value)
  }


  /**
   * 滑动数组内的元素并且合并
   * @param cells 待滑动与合并的数组
   */
  const slide = (cells: Cell[]) => {
    const newCells = cells.filter(cell => cell.value != null) // 滑动：清除数组中空的位置
    for (let i = 0; i < newCells.length - 1; i++) {
      if (newCells[i].value === newCells[i + 1].value) {
        newCells[i].value! *= 2
        newCells.splice(i + 1, 1) // 删除合并的单元格
      }
    }
    // 补充空单元格
    while (newCells.length < 4) {
      newCells.push({ row: 0, col: 0, value: null })
    }
    return newCells
  }


  return {
    chessBoard,
    init,
    handleKeyUp
  }
}